package com.dingding.service.user.facade;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.base.dto.DubboInvokResponseDTO;
import com.dingding.common.core.beans.Oauthinfo;
import com.dingding.common.core.beans.UserCoupon;
import com.dingding.common.core.beans.UserLogin;
import com.dingding.common.core.beans.Userdetail;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.facade.user.dto.evaluate.GetDriverInfoDTO;
import com.dingding.facade.user.dto.usercoupon.ResCoupon;
import com.dingding.facade.user.service.IUserInfoFacade;
import com.dingding.service.user.core.dao.IOauthinfoDao;
import com.dingding.service.user.core.dao.IUserAccountDao;
import com.dingding.service.user.core.dao.IUserCouponDao;
import com.dingding.service.user.core.dao.IUserDetailDao;
import com.dingding.service.user.core.dao.IUserInfoDao;
import com.dingding.service.user.core.dao.IUserIntegralDao;
import com.dingding.service.user.core.dao.IUserLoginDao;
import com.dingding.service.user.core.dao.IVehicleInfoDao;
import com.dingding.service.user.core.enums.OauthNameEnum;
import com.dingding.service.user.core.sql.UserCouponSQL;

/**
 * @ClassName: UserInfoFacade
 * @Description:用户信息操作接口
 * @author zhouxuan
 * @date 2016年4月12日 下午4:13:34
 */
@Component("userInfoFacade")
public class UserInfoFacadeImpl implements IUserInfoFacade {

	private Logger log = Logger.getLogger(this.getClass());

	@Resource(name = "userInfoDao")
	public IUserInfoDao userInfoDao;

	@Resource(name = "userCouponDao")
	private IUserCouponDao userCouponDao;

	// 用户详细信息DAO
	@Resource
	protected IUserDetailDao userDetailDao;

	// 用户登录DAO
	@Resource
	protected IUserLoginDao userLoginDao;

	// 用户账号DAO
	@Resource
	protected IUserAccountDao userAccountDao;

	// 车辆信息DAO
	@Resource
	protected IVehicleInfoDao vehicleinfoDao;

	// 用户积分DAO
	@Resource
	protected IUserIntegralDao userIntegralDao;

	// 用户第三方DAO
	@Resource
	protected IOauthinfoDao oauthinfoDao;

	/**
	 * @Title: getUserCouponNumber
	 * @Description: 获取用户优惠券数目
	 * @param userId
	 *            用户id
	 * @author zhouxuan
	 */
	public int getUserCouponNumber(String userId) {
		if (ToolUtil.isBlank(userId)) {
			return 0;
		}
		return userInfoDao.getUserCouponNumber(userId);
	}

	/**
	 * @Title: setUserCouponNumber
	 * @Description:设置用户优惠券数目
	 * @param @param
	 *            userId 用户id
	 * @param @param
	 *            couponNumber 优惠券数目
	 * @author zhouxuan
	 */
	public boolean setUserCouponNumber(String userId, int couponNumber) {
		if (ToolUtil.isBlank(userId)) {
			return false;
		}
		if (couponNumber > 0) {
			return userInfoDao.setUserCouponNumber(userId, couponNumber);
		}
		return false;
	}

	/**
	 * @Title: setUserCouponNumber
	 * @Description: 增加一张用户优惠券
	 * @param @param
	 *            userId 用户id
	 * @author zhouxuan
	 */
	public boolean addUserCoupon(String userId) {
		if (ToolUtil.isBlank(userId)) {
			return false;
		}
		return userInfoDao.addUserCoupon(userId);
	}
	
	/**
	 * @Title: updateUserCouponNumber
	 * @Description: 减少用户优惠券数量
	 * @param userId 用户id
	 * @author YHQ
	 */
	public boolean updateUserCouponNumber(String userId){
		if (ToolUtil.isBlank(userId)) {
			return false;
		}
		return userLoginDao.reduceCouponNumber(userId);
	}

	/**
	 * @Description: 通过电话号码验证用户是否已经注册
	 * @param tellphone
	 * @author fengshuonan
	 * @return true 用户已经注册 false 用户未注册
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean userIsRegedByPhone(String tellphone) {
		UserLogin userLogin = null;

		try {
			userLogin = this.userLoginDao.getUserLoginByProperty("userName", tellphone);
			if (userLogin == null) {
				return false;
			}
		} catch (Exception e) {
			log.error("查询用户是否注册过时出错！UserInfoFacadeImpl：userIsRegedByPhone（）", e);
		}

		return true;
	}

	/**
	 * @Description: 添加用户
	 * @param tellPhone
	 *            电话号码
	 * @param weChatId
	 *            微信openId
	 * @author fengshuonan
	 * @return boolean true 添加成功 false 添加失败
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean addUser(String tellPhone, String weChatId) {

		String userLoginId = ToolUtil.getUid();
		try {
			// 首次注册初始化用户所有信息
			// 添加用户
			this.userLoginDao.addUserLogin(tellPhone, userLoginId, weChatId);

			// 添加用户详细信息
			this.userDetailDao.addUserDetail(tellPhone, userLoginId);

			// 添加用户账户信息
			this.userAccountDao.addUserAccount(userLoginId);

			// 添加用户积分信息
			this.userIntegralDao.addUserIntegral(userLoginId);

			// 添加用户车辆信息
			this.vehicleinfoDao.addVehicleInfo(userLoginId);

			// 添加注册来源信息
			this.oauthinfoDao.save(new Oauthinfo(userLoginId, OauthNameEnum.WECHAT.getName()));

			return true;
		} catch (Exception e) {
			log.error("初始化用户出现异常");
		}

		// 首先判断
		return false;
	}

	/**
	 * 
	 * 订单完成后，乘客评价页面需要显示车主信息及部分订单信息，当前接口由此产生
	 * 
	 * 由于当前接口所需要的车主信息需要依赖顶大信息所以获取订单信息也在此接口完成
	 * 
	 * @Title: getDriverInfo_And_OrderInfo
	 * @param orderId 订单ID
	 * @param registrationType 订单类型 1:私家车 2:出租车 3:专车
	 * @author CHEHUANBO
	 * @return GetDriverInfoDTO 获取到的车主信息及相关订单信息
	 * 
	 */
	public DubboInvokResponseDTO<GetDriverInfoDTO> getDriverInfo_And_OrderInfo(String orderId,Integer registrationType) {

		DubboInvokResponseDTO<GetDriverInfoDTO> baseQueryResponseDTO = new DubboInvokResponseDTO<GetDriverInfoDTO>();

		if (ToolUtil.isBlank(orderId)) {
			baseQueryResponseDTO.setCode(302);
			baseQueryResponseDTO.setErrorMessage("获取到的车主信息及相关订单信息出现异常！原因是：订单ID为空");
			return baseQueryResponseDTO;
		} else {
			baseQueryResponseDTO.setCode(200);
			baseQueryResponseDTO.setResponseData(this.userInfoDao.getDriverInfo_And_OrderInfo(orderId,registrationType));
		}

		return baseQueryResponseDTO;

	}

	/**
	 * @Title: getUserCouponList
	 * @Description:获取用户优惠券列表
	 * @author zhouxuan
	 * @return List<UserCoupon>
	 */
	@Override
	public List<UserCoupon> getUserCouponList(String userId) {
		return this.userCouponDao.getUserCouponList(userId);
	}

	/**
	 * 
	 * @Title: getUserDetail
	 * @Description: 根据用户Id获取用户详情
	 * @param userId
	 *            用户Id
	 * @author YHQ
	 * @return Userdetail 用户详情
	 * 
	 */
	@Override
	@Transactional(readOnly=true)
	public Userdetail getUserDetail(String userId) {

		// 创建用户详情对象
		Userdetail userdetail = null;
		Criterion criterion = Restrictions.eq("loginId", userId);

		try {
			userdetail = this.userDetailDao.queryCriteriaUnResult(criterion);
		} catch (Exception e) {
			log.error("查询用户详情出现异常, 类：" + this.getClass() + " 方法：getUserDetail()", e);
		}

		if (userdetail == null) {
			log.error("不存在该用户的详情, 类：" + this.getClass() + " 方法：getUserDetail()");
			return null;
		}
		return userdetail;
	}

	/**
	 * 
	 * @Title: updateUserDetail 
	 * @Description: 更新用户详情
	 * @param userdetail 用户详情对象
	 * @author YHQ 
	 * @since V2.3.0
	 * @return boolean    返回类型
	 * 
	 */
	@Transactional(propagation=Propagation.REQUIRED)
	public boolean updateUserDetail(Userdetail userdetail){
		
		try {
			this.userDetailDao.update(userdetail);
			
			return true;
		} catch (Exception e) {
			log.error("更新用户详情时出现异常   类："+this.getClass()+" updateUserDetail", e);
		}
		
		return false;
	}
	
	/**
	 * 
	 * @Title: getResCoupon 
	 * @Description: 根据优惠券Id获取搭乘时要使用的优惠券信息
	 * @param ucId 优惠券Id
	 * @author YHQ 
	 * @return ResCoupon  优惠券信息
	 * 
	 */
	@Override
	@Transactional(readOnly=true)
	public ResCoupon getResCoupon(String ucId) {
		
		//获取出行券列表
		Object[] object = userCouponDao.sqlQueryUnResultObj(UserCouponSQL.GET_COUPON_INFO, ucId);
		
		//判断获取的出行券列表是否为空
		if(object != null){
			
			return objectToCouponInfo(object);
		}
		
		return null;
	}
	
	
	/**
	 * 
	 * @Title: getResCoupon 
	 * @Description: 根据优惠券Id获取搭乘时要使用的优惠券信息
	 * @param ucId 优惠券Id
	 * @author YHQ 
	 * @return ResCoupon  优惠券信息
	 * 
	 */
	@Override
	@Transactional(readOnly=true)
	public UserCoupon getUserCoupon(String userId) {
		
		Criterion criterion = Restrictions.and(Restrictions.eq("loginId", userId),Restrictions.eq("couponType", 2),Restrictions.eq("couponStatus", 2));
		
		try {
			List<UserCoupon> userCoupons = userCouponDao.queryCriteriaList(criterion);
			
			if(userCoupons != null && userCoupons.size() > 0){
				return userCoupons.get(0);
			}
			
		} catch (Exception e) {
			log.error("根据用户Id获取用户出行券时出现异常   类："+this.getClass() + " line: 326");
		}
		
		return null;
	}
	

	/**
	 * @Title: objectToCoupon 
	 * @Description: 将Object[]类型的转为coupon类型
	 * @param 我的出行券列表 objects
	 * @author YHQ
	 * @return List<ResCoupon>    返回类型 
	 * @throws
	 */
	public ResCoupon objectToCouponInfo(Object[] object){
		
		//创建出行券对象
		ResCoupon resCoupon = new ResCoupon();
		
		//用户优惠券Id
		if(object[0] != null){
			resCoupon.setUcId(object[0].toString());
		}
		//优惠金额
		if(object[1] != null){
			resCoupon.setCouponMoney(ToolUtil.castDouble(object[1]));
		}
			
		return resCoupon;
	}

	/**
	 * 
	 * @Title: updateUserCoupon 
	 * @Description: 修改用户优惠券信息 
	 * @param ucId 用户优惠券Id
	 * @author YHQ 
	 * @return boolean true:修改成功   false:修改失败
	 * 
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public boolean updateUserCoupon(String ucId) {
		
		UserCoupon userCoupon = null;
		try {
			
			userCoupon = userCouponDao.getById(ucId);
			
			if(userCoupon != null){
				userCoupon.setCouponStatus(3);
			}
			
			return true;
		} catch (Exception e) {
			
			log.error("修改用户优惠券状态出现异常   类："+this.getClass()+" updateUserCoupon()", e);
		}
		
		return false;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public UserLogin addUser(String tellphone) {
		
		String userLoginId = ToolUtil.getUid();
		UserLogin ul = null;
		try {
			// 首次注册初始化用户所有信息
			// 添加用户
			ul = this.userLoginDao.addUserlogin(tellphone, userLoginId, "0");

			// 添加用户详细信息
			this.userDetailDao.addUserDetail(tellphone, userLoginId);

			// 添加用户账户信息
			this.userAccountDao.addUserAccount(userLoginId);

			// 添加用户积分信息
			this.userIntegralDao.addUserIntegral(userLoginId);

			// 添加用户车辆信息
			this.vehicleinfoDao.addVehicleInfo(userLoginId);

			// 添加注册来源信息
			this.oauthinfoDao.save(new Oauthinfo(userLoginId, OauthNameEnum.WECHAT.getName()));

			return ul;
		} catch (Exception e) {
			log.error("初始化用户出现异常",e);
			return null;
		}
	}

	@Override
	public UserLogin addUserByWechat(String tellphone, String wechatId) {
		String userLoginId = ToolUtil.getUid();
		UserLogin ul = null;
		try {
			// 首次注册初始化用户所有信息
			// 添加用户
			ul = this.userLoginDao.addUserlogin(tellphone, userLoginId, wechatId);

			// 添加用户详细信息
			this.userDetailDao.addUserDetail(tellphone, userLoginId);

			// 添加用户账户信息
			this.userAccountDao.addUserAccount(userLoginId);

			// 添加用户积分信息
			this.userIntegralDao.addUserIntegral(userLoginId);

			// 添加用户车辆信息
			this.vehicleinfoDao.addVehicleInfo(userLoginId);

			// 添加注册来源信息
			this.oauthinfoDao.save(new Oauthinfo(userLoginId, OauthNameEnum.WECHAT.getName()));

			return ul;
		} catch (Exception e) {
			log.error("初始化用户出现异常",e);
			return null;
		}
	}
	
}
